package br.com.seosoft.simplecalcfinan.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.Button;
import android.widget.DatePicker;
import br.com.seosoft.simplecalcfinan.R;
import br.com.seosoft.simplecalcfinan.geral;

public class DatePickerFragment extends DialogFragment implements
		DatePickerDialog.OnDateSetListener {

	Button btnData;
	String dataString;
	Date data;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current date as the default date in the picker

		btnData = (Button) getActivity().findViewById(R.id.btnData);
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);

		if (btnData.getText().equals("Data")) {
			// Create a new instance of DatePickerDialog and return it

			return new DatePickerDialog(getActivity(), this, year, month, day);
		} else {

			dataString = btnData.getText().toString().trim();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",
					Locale.getDefault());

			try {
				data = format.parse(dataString);

				c.setTime(data);
				year = c.get(Calendar.YEAR);
				month = c.get(Calendar.MONTH);
				day = c.get(Calendar.DAY_OF_MONTH);

				return new DatePickerDialog(getActivity(), this, year, month,
						day);
			} catch (ParseException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
				return new DatePickerDialog(getActivity(), this, year, month,
						day);
			}

		}

	}

	public void onDateSet(DatePicker view, int year, int month, int day) {
		// Do something with the date chosen by the user
		int mes = month + 1;
		String day_str;
		String mes_str;

		if (mes < 10) {
			mes_str = "0" + String.valueOf(mes);
		} else {
			mes_str = String.valueOf(mes);
		}

		if (day < 10) {
			day_str = "0" + String.valueOf(day);
		} else {
			day_str = String.valueOf(day);
		}

		Log.v(geral.LogCat, "DATA : MES: " + mes_str);
		Log.v(geral.LogCat, "DATA : DAY: " + day_str);

		btnData.setText(new StringBuilder().append(year).append("-")
				.append(mes_str).append("-").append(day_str));
	}
}
